/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Main page of A Group
 * Contains Group name, description, total member count, newsgroup
 * If a user is not a member of this group, there should be a button named " Join this group"
 * If user is a member, have "Leave this group" button available
 * 
 * @author Kyu
 */
public class GroupAServlet extends HttpServlet {
   
    String name = "Group A"; // current group
    String description = "This is description for group A"; // description 
    String totalMem = "12"; // number of total members in the group
    String creator = "Lee";   // person made the group
    
    String[] topics = {"Photography", "Cooking", "Java"};
    String[] authors = {"Karl", "Jinlin", "Rodrigo", "Kyu"};
    String[] titlesUnderTopicPhotogrphy = {"my picture today", "Best Picture", "Introducing myself", "Lunch this Sunday"};
    String[] messageContents = {"Very often when you write code, you want the same block of code to run over and over again in a row." +
            "Instead of adding several almost equal lines in a script we can use loops to perform a task like this."};
    String[] posterEmail = {"kyueun_lee@hotmail.com", "abc@google.com", "icebaby@yahoo.com"};
    String postDateTime = "18:23:30 3rd Nov 2007";
    
    
    /** 
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession httpSession = request.getSession(true);
        
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here */
            out.println("<html>");
            out.println("<head>");
            //out.println("<title>Servlet GroupAServlet</title>");  
            
            out.println("<link rel=\"stylesheet\" href=\"inbox.css\" type=\"text/css\">");
            generateInlineJS(out);
            CSSGenerator.generateNewsGroupMainPageInlineCSS(out);
            
            out.println("</head>");
            out.println("<body>");
            //out.println("<h1>Servlet GroupAServlet at </h1>");
            /*
            out.println("<h2>Name: " + name + "</h2>");
            out.println("Description: " + description);
             */
             out.println(
                     "<center>" +                     
                     "<table width=\"60%\" border>" + /* outter table */
                     "  <td>"+
                     /* first row */
                    // "  <table>" + /* inner table */
                     "    <tr>" + 
                     "     <td><p class=\"ngroupTitle\"> " +
                     "      Name: </p></td>" +
                     "      <td>" + name + "</td>" +
                     "      <td>" + 
                     "       <input type=\"button\" aligh = right id=\"JoinThisGroup\" value=\"Join\" onClick=\"" + 
                                // TODO: have a popup window say "Welcome to this group"
                             "window.open(\'GroupNewPostServlet\', '_blank', 'width=500,height=400,status=1,menubar=0,resizable=0 '); return false;\">" +
                      "     </td>" +
                     "    </tr>" + 
                     "   <tr>" + 
                     "      <td><p class=\"ngroupTitle\"> " +
                     "      Description: </p></td>" + 
                     "     <td>" + description + "</td>" +
                        "      <td>" + "</td>" +
                     "    </tr>" + 
                     "    <tr>" + 
                     "      <td><p class=\"ngroupTitle\"> " +
                     "      Total Member: </p></td>" + 
                     "     <td>" + totalMem + "</td>" +
                     "     <td>" +  "<a href=\"GroupAllMembers\">View All Members</a></td>" +
                     "    </tr>" + 
                     "    <tr>" + 
                     "     <td><p class=\"ngroupTitle\"> " +
                     "      Creator: </p></td>" + 
                     "     <td>" + creator + "</td>" +
                           "      <td>" + "</td>" +
                     "   </tr>" +
                    
                     /* second row */
                     "<tr></tr>" +
                     "  <tr>" +
                    "    <td> " +
                    "       <p class=\"ngroupTitle\">" +
                    "           NewsGroup:" +
                    "       </p>" +
                    "    </td>" +
                          "      <td>" + "</td>" +
                                "      <td>" + 
                                "       <input type=\"button\" id=\"New_message\" value=\"New Message\" onClick=\"" + 
                                "window.open(\'GroupNewPostServlet\', '_blank', 'width=500,height=400,status=1,menubar=0,resizable=0 '); return false;\">" +
                                                            
                                "</td>" /*Button to add more messages*/ 
                     );

            
             /**
              * Newsgroup Topics
              */
             for (int i = 0; i < topics.length; i++)
             {
                 /**
                  * TODO:                  
                  * Reply(s)
                  * Order messages in order of time stamp
                  */
                 
                     /* third row */    
                   out.println(
                     "<tr>" +     
                     "  <td></td>"+
                     "  <td>" +
                     "  <p class=\"ngroupSectionLinkText\">" +
                     "  <a href=\"GroupAServlet?topics=" + topics[i] +"\">"
                     );
                  out.println(topics[i]);
                  out.println(
                     " </a>" +
                     " </p>" +
                     "  </td>" +        
                     "</tr>"
                     );  
                  
                  if((request.getParameter("topics") != null) && 
                          (request.getParameter("topics").compareToIgnoreCase("Photography") == 0 )&&
                          (topics[i].compareToIgnoreCase("Photography")== 0))
                  {
                       for(int j = 0; j < titlesUnderTopicPhotogrphy.length; j++)
                      {
                              out.println(
                             "<tr>" +     
                             "  <td>" +
                             "  </td>" +
                             "  <td>" +
                             "  <p class=\"ngroupSectionLinkText\">" +
                             "  <a href=\"GroupAServlet?topics=   " + titlesUnderTopicPhotogrphy[j] + "&" + 
                             "topicIndex=" + j + "\" " +
                             "target=\"_blank\" onclick=\"" +
                             "window.open(this.href, '_blank', 'width=500,height=400,status=1,menubar=0,resizable=0 '); return false;\">"

                             );
                          
                             out.println(titlesUnderTopicPhotogrphy[j]);
                             out.println(
                             " </a>" +
                             " </p>" +
                             "  </td>" +        
                             "</tr>"
                             );  
                      }
                 
                  }
                 
             }
             
            /* end of table */
            out.println(
                     "  </td>"+
                     "</table>" + "<center>");
            
              
            out.println("</body>");
            out.println("</html>");
           
        } finally { 
            out.close();
        }
    } 
    
      protected void handlePopupMessage(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
         String topic;
         int topicIndex;
         
         topicIndex =Integer.parseInt(request.getParameter("topicIndex"));
         topic =  titlesUnderTopicPhotogrphy[topicIndex];
         
         response.setContentType("text/html;charset=UTF-8");
         PrintWriter out = response.getWriter();
         try {
             
            out.println("<html>");
            out.println("<head>");
            out.println("<title>News Group Post</title>");             
            CSSGenerator.generateNewsGroupPopupReplayInlineCSS(out);            
            out.println("</head>");
            out.println("<body>");        
            
            out.println(
            //"<form>" +
            "<center>" +
            "<table height=\"380\" width=\"480\" border=\"0\">" +// style=\"border-color:#336699 \" border=\""+ngroupOuterTableBorderWidth+"\">" +
            "<tr height=\"10\">" +
            "   <td colspan=\"4\">" +
            "       <p class=\"ngroupMessageLabel\"> " +
            "       Message Topic" +     // title
            "       </p>"  +
            "   </td>" +
            "</tr>"+   
            "<tr height=\"10\">" +
            "   <td colspan=\"4\">" +
            "   <input type=\"text\" size=\"72\" name=messageTitle readonly value=\" " +
            topic +
            "   \">" +
            "   </td>" +
            "</tr>" +
            
            "<tr height=\"10\" >" +
            "   <td>" +
            "       <p class=\"ngroupMessageLabel\"> " +
            "       Message Body" +     // Message Body
            "       </p>"  +
            "   </td>" +
            "   <td colspan=\"3\" align =\"right\">" + 
            "       <p class =\"postInfo\">" +
            "       Posted by " + "<a href=\"UserServlet?" + posterEmail[topicIndex] +"\" target=\"_blank\">"+
                    authors[topicIndex] + "</a>" +
            " at " +  postDateTime + ". " +
            "       </p>" +
            "   </td>"+
            "</tr>"+
                    
            // message body        
            "<tr height=\"40\">" +
            "   <td valign=\"top\" colspan=\"4\">" +
            //"   <input type=\"TEXTAREA\"  readonly " +
            "   <textarea rows=\"10\" cols=\"56\" readonly " +        
            "    name=messageBody >" +
            messageContents[topicIndex] +
            "   </textarea>" +
            "   </td>" +
            "</tr>" +
             
            // reply
             "<tr height=\"10\" >" +
            "   <td colspan=\"4\">" +
            "       <p class=\"ngroupMessageLabel\"> " +
            "       Reply" +     // reply
            "       </p>"  +
            "   </td>" +
            "</tr>"+
            "<tr height=\"40\">" +
            "   <td valign=\"top\" colspan=\"4\">" +
            "<form name=\"replyForm\" method=\"POST\" action=\"SavePostToDBServlet\">" +
            //"   <input type=\"TEXTAREA\"  readonly " +
            "   <textarea rows=\"6\" cols=\"56\" " +        
            "    name=messageReply >" +
            "</textarea>" +
            "   </td>" +
            "</tr>" +
                    
            "<tr height=\"7\" valign=\"top\">" +          //  |
            "   <td width=\"120\" valign=\"middle\">" +   //  | these two needs to be sorted out
            //"   &nbsp" +
            "   <p class=\"copyRight\"> ClassNet© 2007  </p>"  +
            "   </td>" +
            "   <td width=\"120\">&nbsp</td>" +
            "   <td width=\"200\" align =\"right\" valign=\"top\" >"+
           // "<form name=\"replyForm\" method=\"POST\" action=\"PostServlet\">" +
            " <input type=\"submit\" name=\"postReply\" value=\"Reply\" >" +//onClick=\"window.close()\">" +
            "</form>" +
          //  "   <button>Reply</button>"+  
            "   </td>" +
            "   <td width=\"40\" align =\"right\" valign=\"top\">"+
            "   <button onclick=\"window.close()\">Close</button>"+  
            "   </td>" +                    
            "</tr>" +           
            "</table>"+
            "</center>"
            
            );
              
            out.println("</body>");
            out.println("</html>");
            
        } finally { 
            out.close();
        }
     }
            
    private void generateInlineJS(PrintWriter out)
    {
        out.println(
                 "<script language=\"javascript\"> " +
         "function loadwindow(target)" +
         "{" +
         "       window.open(target,\"\",\"width=800,height=600,status=1,menubar=0,resizable=1\");" +
        /*
         "  switch(target) " +
         "  {"+
         "      case 1: window.open(\"/soc/Resume.pdf\",\"\",\"width=800,height=600,status=1,menubar=0,resizable=1\");" +
	 "       break;" +
	 "      default: break;" +
	 "  }" +
        */
         "}" +
         "</script>"
       );
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        if(request.getParameter("topicIndex") == null) // go to news group main page
        {
            //name = request.getParameter("GroupName");
            //description = request.getParameter("Description");
                    
            processRequest(request, response);  // rename the method
        }        
        else
        {
            handlePopupMessage(request,response);  // popup a window for reply            
        }
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Servlet for a Group page request";
    }
    // </editor-fold>
}
